﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CLVisionCameraControl;
using MvCameraControl;
using static System.Net.Mime.MediaTypeNames;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private readonly object saveImageLock = new object();
        private IImage frameForSave;

        ICLVisionCameraControl cLVisionCameraControl = new HIKAreaScanCameraControl();



        ICLVisionCamera cLVisionCamera;

        private void button1_Click(object sender, EventArgs e)
        {
            cLVisionCameraControl.SearchDevice(out List<ICLVisionCamera> cLVisionCameraList, out _, out string text);
            cLVisionCamera = cLVisionCameraList[0];
            cLVisionCamera.OpenDeviceBySerialNumber(cLVisionCamera.CLVisionCameraInfo.SerialNumber, out _, out text);
            //  cLVisionCamera.HWnd = pictureBox1.Handle;
            // cLVisionCamera.AcquisitionContinues(out _, out text);
            // cLVisionCamera.StartGrab(out _, out text);

            //if (cLVisionCameraList[0] is HIKAreaScanCamera generalCamera)
            //{
            //    generalCamera.EventGrabBackHIKImage += (s) =>
            //    {

            //        //Bitmap bitmap = new Bitmap(Convert.ToInt32( s.Width), Convert.ToInt32(s.Height), PixelFormat.Format24bppRgb);

            //        //// 锁定 Bitmap 的数据区域以便写入像素数据
            //        //BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, Convert.ToInt32(s.Width), Convert.ToInt32(s.Height)), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            //        //try
            //        //{
            //        //    // 获取 Bitmap 数据的指针
            //        //    IntPtr ptr = bitmapData.Scan0;

            //        //    // 将像素数据复制到 Bitmap 中
            //        //    System.Runtime.InteropServices.Marshal.Copy(s.PixelData, 0, ptr, s.PixelData.Length);
            //        //}
            //        //finally
            //        //{
            //        //    // 解锁 Bitmap 的数据区域
            //        //    bitmap.UnlockBits(bitmapData);
            //        //}
            //        lock (saveImageLock)
            //        {
            //            try
            //            {
            //                frameForSave = s.Clone() as IImage;
            //                // pictureBox1.Image = frameForSave.ToBitmap();
            //            }
            //            catch (Exception)
            //            {

            //            }
            //        }
            //        pictureBox2.Image = s.ToBitmap();
            //        // pictureBox2.Image = ConvertToBmp(s.PixelDataPtr, s.PixelData, Convert.ToInt32(s.Width), Convert.ToInt32(s.Height), PixelFormat.Format24bppRgb);
            //    };
            //}
        }

        private void button2_Click(object sender, EventArgs e)
        {
            cLVisionCamera.StopGrab(out _, out string text);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            cLVisionCamera.SetTriggerMode(EnumTriggerMode.On, out _, out _);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            // cLVisionCamera.AcquisitionContinues(out _, out string text);
            IntPtr pixelPtr = pictureBox1.Handle;
            cLVisionCamera.AcquireImageContinuous(pixelPtr, out _, out _);


            cLVisionCamera.EventGrabBackBitmapImage += (bitmap) =>
            {
                this.BeginInvoke((MethodInvoker)delegate
                 {
                     pictureBox2.Image = bitmap;
                 });
            };




        }

        private void button5_Click(object sender, EventArgs e)
        {
            cLVisionCamera.StartGrab(out _, out string text);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            cLVisionCamera.TriggerSoftwareOnce(out _, out string text);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            cLVisionCamera.CloseDevice(out _, out string text);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            cLVisionCamera.CloseDevice(out _, out string text);
        }

        public Bitmap ConvertToBmp(IntPtr pixelPtr, byte[] pixelData, int width, int height, PixelFormat pixelFormat)
        {
            // 根据像素格式计算步幅（每行字节数必须是4的倍数）
            int bitsPerPixel = System.Drawing.Image.GetPixelFormatSize(pixelFormat);
            int stride = (width * bitsPerPixel / 8 + 3) & ~3;



            // 创建 Bitmap 对象并锁定内存
            using (Bitmap bmp = new Bitmap(width, height, pixelFormat))
            {
                BitmapData bmpData = bmp.LockBits(
                    new Rectangle(0, 0, width, height),
                    ImageLockMode.WriteOnly,
                    pixelFormat
                );

                unsafe
                {
                    // 从 IntPtr 或 byte[] 复制数据到 Bitmap
                    if (pixelPtr != IntPtr.Zero)
                    {
                        // 直接复制内存
                        Buffer.MemoryCopy(
                            (void*)pixelPtr,      // 源指针
                            (void*)bmpData.Scan0, // 目标指针
                            bmpData.Stride * height,
                            stride * height
                        );
                    }
                    else if (pixelData != null)
                    {
                        // 从 byte[] 复制
                        Marshal.Copy(pixelData, 0, bmpData.Scan0, pixelData.Length);
                    }
                }


                bmp.UnlockBits(bmpData);
                return bmp;

                // 保存为 BMP（自动处理文件头）
                //  bmp.Save(outputPath, ImageFormat.Bmp);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (cLVisionCamera is HIKAreaScanCamera generalCamera)
            {
                EnumImageFormatType enumImageFormatType = EnumImageFormatType.Png;
                generalCamera.SaveImageToFile(@"C:\Users\Public\Desktop\" + "test." + enumImageFormatType.ToString(), frameForSave, enumImageFormatType, CFAMethod.Equilibrated, out _, out _);
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            cLVisionCamera.GetParamExposure(out float value, out _, out _);

            numericUpDown1.Value = Convert.ToDecimal(value);
        }

        private void button10_Click(object sender, EventArgs e)
        {
            cLVisionCamera.GetParamGain(out float value, out _, out _);

            numericUpDown2.Value = Convert.ToDecimal(value);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            cLVisionCamera.GetParamPixelFormat(out EnumPixelFormat value, out _, out _);
            comboBox1.Text = value.ToString();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            cLVisionCamera.GetParamFrameRate(out float value, out _, out _);
            numericUpDown3.Value = Convert.ToDecimal(value);
        }


        private void button12_Click(object sender, EventArgs e)
        {
            float f = Convert.ToSingle(numericUpDown1.Value);
            cLVisionCamera.SetParamExposure(f, out _, out _);
        }
        private void button13_Click(object sender, EventArgs e)
        {
            float f = Convert.ToSingle(numericUpDown2.Value);
            cLVisionCamera.SetParamGain(f, out _, out _);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            EnumPixelFormat enumPixelFormat = (EnumPixelFormat)Enum.Parse(typeof(EnumPixelFormat), comboBox1.SelectedItem.ToString());
            cLVisionCamera.SetParamPixelFormat(enumPixelFormat, out _, out _);
        }

        private void button16_Click(object sender, EventArgs e)
        {
            float f = Convert.ToSingle(numericUpDown3.Value);
            cLVisionCamera.SetParamFrameRate(f, out _, out _);
        }

        private void button17_Click(object sender, EventArgs e)
        {
            cLVisionCamera.FeatureSave(@"C:\Users\Public\Desktop\1.txt", out _, out _);
        }

        private void button18_Click(object sender, EventArgs e)
        {
            cLVisionCamera.FeatureLoad(@"C:\Users\Public\Desktop\1.txt", out _, out _);

        }

        private void button19_Click(object sender, EventArgs e)
        {
            cLVisionCamera.StopGrab(out _, out _);
        }

        private void button20_Click(object sender, EventArgs e)
        {


            Bitmap bitmap = cLVisionCamera.AcquireOneFrameImage(out _, out string _);
            pictureBox1.Image = bitmap;
        }

        private void button21_Click(object sender, EventArgs e)
        {
            cLVisionCameraControl.SearchDevice(out List<ICLVisionCamera> cLVisionCameraList, out _, out string text);
            cLVisionCamera = cLVisionCameraList[0];
            cLVisionCamera.OpenDeviceBySerialNumber(cLVisionCamera.CLVisionCameraInfo.SerialNumber, out _, out text);
            cLVisionCamera.StartGrab(out _, out text);
        }
    }
}
